package com.asset.dispoal.business.bsEvidenceRecognition.service.commom;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.mapper.BsRecognitionAllRecordMapper;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.mapper.BusinessDataManageMapper;
import com.asset.dispoal.business.match.dto.MatchRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.redis.commands.IRedisExtCommands;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class EvidenceMatchResultCommand implements BaseCommand<MatchRequest, Result> {

    @Autowired
    private IRedisExtCommands redisExtCommands;

    @Autowired
    BusinessDataManageMapper businessDataManageMapper;

    @Autowired
    BsRecognitionAllRecordMapper bsRecognitionAllRecordMapper;

    @Autowired
    BaseIdeable<String> snowFlak;

    @Override
    public Result execute(MatchRequest matchRequest) {
        String requestKey = matchRequest.getData().getRequestKey();
        String batchId = requestKey.substring(0, requestKey.length() - 2);
        Integer count = bsRecognitionAllRecordMapper.checkState(batchId);
        if (count == 0) {
            bsRecognitionAllRecordMapper.updateStateAllByBatchId(batchId);
        }
        if (matchRequest.isFaild()) {
            redisExtCommands.hdel(6, "ocr_data", requestKey);
            redisExtCommands.hdel(6, "ocr_before", requestKey);
            bsRecognitionAllRecordMapper.updateStateByBatchId(batchId, "0");
            businessDataManageMapper.updateEvidenceRegnitionStateByFaild(batchId);
            return Result.ok();
        }
        String responseKey = matchRequest.getData().getResponseKey();
        String notifyKey = responseKey + "_" + requestKey;
        String matchResult = redisExtCommands.hget(6, "notify_key", notifyKey);
        JSONObject jsonObj = JSON.parseObject(matchResult);
        Set<String> evidenceIdSet = jsonObj.keySet();

        String assetInstBatchId = bsRecognitionAllRecordMapper.getAssetBatchIdByBatchId(batchId);
        List<Map<String, String>> mapList = businessDataManageMapper.queryDataDetail(assetInstBatchId);
        List<Map<String, Object>> queryResult = businessDataManageMapper.queryResult(assetInstBatchId, mapList);
        for (String evidenceId : evidenceIdSet) {
            JSONObject evidenceMatchJson = jsonObj.getJSONObject(evidenceId);
            String evidenceItemId = evidenceMatchJson.getString("evidenceItemId");
            evidenceMatchJson.remove("evidenceItemId");
            Set<String> params = evidenceMatchJson.keySet();
            String state = CollectionUtil.isEmpty(params) ? "0" : "1";
            businessDataManageMapper.updateEvidenceRegnitionStateByEvidenceId(evidenceId, evidenceItemId, state);
            String continued = businessDataManageMapper.getContByEvidenceId(evidenceId);
            for (String param : params) {
                JSONArray matchResultArr = evidenceMatchJson.getJSONArray(param);
                for (Object matchResultObj : matchResultArr) {
                    String genMapperId = snowFlak.generateId();
                    businessDataManageMapper.insertEvidenceMapperRecord(genMapperId, evidenceId, param, matchResultObj);
                    if ("1".equals(continued)) {
                        businessDataManageMapper.insertEvidenceMapper(genMapperId, evidenceId, param, matchResultObj);
                    } else {
                        //不兼容后续证据
                        List<String> successIdList = queryResult.stream().filter(query -> matchResultObj.equals(query.get(param))).map(query -> (String) query.get("contractId")).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(successIdList)) {
                            for (String contractId : successIdList) {
                                businessDataManageMapper.insertEvidenceMapper(snowFlak.generateId(), evidenceId, "contractId", contractId);
                            }
                        }
                    }
                }
            }
        }
        bsRecognitionAllRecordMapper.updateStateByBatchId(batchId, "1");

        redisExtCommands.hdel(6, "ocr_data", requestKey);
        redisExtCommands.hdel(6, "ocr_before", requestKey);
        redisExtCommands.hdel(6, "notify_key", notifyKey);
        return Result.ok();
    }
}
